package com.masterclient.app.modules.goods.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.bumptech.glide.Glide;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselibrary.bean.goods.CommodityComment;
import com.eoner.baselibrary.bean.goods.CommodityDetailData;
import com.eoner.baselibrary.bean.goods.CommodityShareMessage;
import com.eoner.baselibrary.bean.goods.CouponMessage;
import com.eoner.baselibrary.bean.goods.SellerMessage;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.common.config.Config;
import com.eoner.commonbean.product.ProductMessage;
import com.eoner.commonbean.product.ProductTag;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.sobot.SobotHyperlinkListener;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.base.MainViewHolder;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.cart.beans.AddShopCartBean;
import com.masterclient.app.modules.goods.ActivityDialog;
import com.masterclient.app.modules.goods.CommodityCouponDialog;
import com.masterclient.app.modules.goods.adapter.CommodityDetailBannerAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailCommentAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailDescriptionAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailFansTimeLimitAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailFootAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailInformationAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailRecommendProductAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailSellerAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailServiceAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityDetailTimeLimitAdapter;
import com.masterclient.app.modules.goods.adapter.CommodityServiceAdapter;
import com.masterclient.app.modules.goods.beans.ShareProductBean;
import com.masterclient.app.modules.goods.contract.CommodityDetailContract;
import com.masterclient.app.modules.goods.contract.CommodityDetailPresenter;
import com.masterclient.app.modules.goods.widget.PurchaseDialog;
import com.masterclient.app.modules.goods.widget.SkuSelectDialog;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.ImageDialog;
import com.masterclient.app.widget.MaterialBadgeTextView;
import com.masterclient.app.widget.ShareCommonDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.ConsultingContent;
import com.sobot.chat.api.model.Information;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

//@Route(path = AroutePath.COMMODITY_DETAIL_ACTIVITY)
public class CommodityDetailActivity extends BaseActivity<CommodityDetailPresenter> implements CommodityDetailContract.View {

    @BindView(R.id.root)
    View root;
    @BindView(R.id.title_layout)
    View title_layout;
    @BindView(R.id.iv_back_top)
    View iv_back_top;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_share)
    ImageView tv_share;
    @BindView(R.id.brand_introduction)
    View brandIntroduction;
    @BindView(R.id.material)
    View material;
    @BindView(R.id.ll_jump_con)
    LinearLayout ll_jump_con;

    @BindView(R.id.tv_tag_goods)
    View tvTagGoods;
    @BindView(R.id.tv_tag_comment)
    View tvTagComment;
    @BindView(R.id.tv_tag_detail)
    View tvTagDetail;
    @BindView(R.id.tv_tag_recommend)
    View tvTagRecommend;
    @BindView(R.id.tv_tag_goods1)
    TextView tvTagGoods1;
    @BindView(R.id.tv_tag_comment1)
    TextView tvTagComment1;
    @BindView(R.id.tv_tag_detail1)
    TextView tvTagDetail1;
    @BindView(R.id.tv_tag_recommend1)
    TextView tvTagRecommend1;

    //底部的按钮 正常商品
    @BindView(R.id.normal_layout)
    View normal_layout;
    @BindView(R.id.normal_add_cart_btn)
    TextView normal_add_cart_btn;
    @BindView(R.id.normal_buy_now_btn)
    TextView normal_buy_now_btn;

    //会员按钮
    @BindView(R.id.vip_bottom_layout)
    View vip_bottom_layout;
    @BindView(R.id.vip_buy)
    View vip_buy;
    @BindView(R.id.vip_buy_name)
    TextView vip_buy_name;
    @BindView(R.id.vip_save_money)
    TextView vip_save_money;
    @BindView(R.id.vip_sell)
    View vip_sell;
    @BindView(R.id.vip_earn_name)
    TextView vipEarnName;
    @BindView(R.id.vip_earn_money)
    TextView vip_earn_money;
    //单个按钮的情况
    @BindView(R.id.single_btn_layout)
    View single_btn_layout;
    @BindView(R.id.single_btn)
    TextView single_btn;

    //底部购物车和客服
    @BindView(R.id.ll_bottom)
    View ll_bottom;
    @BindView(R.id.rl_kefu)
    View rl_kefu;
    @BindView(R.id.rl_cart)
    View rl_cart;
    @BindView(R.id.tvCartBadge)
    MaterialBadgeTextView tvCartBadge;

    @BindView(R.id.rl_recommend)
    View rl_recommend;
    @BindView(R.id.view_live)
    View viewLive;

    //赠送权相关
    @BindView(R.id.commodity_detail_zsq_btn)
    TextView zsqBtn;
    @BindView(R.id.ll_bottom_zsq)
    RelativeLayout zsqBottomView;

    @Autowired(name = "id")
    String id;

    //埋点
    @Autowired(name = "anchor_id")
    String anchor_id;
    @Autowired(name = "button_name")
    String button_name;
    @Autowired(name = "isAnalytics")
    boolean isAnalytics;
    @Autowired(name = "isPlayBack")
    boolean isPlayBack;


    @Autowired(name = "product_sourcepage")
    String product_sourcepage;
    @Autowired(name = "source_page_id")
    String sourcePageId;
    @Autowired(name = "source_page")
    String sourcePage;
    @Autowired(name = "source_module")
    String sourceModule;
    @Autowired(name = "source_element")
    String sourceElement;
    @Autowired(name = "source_position")
    String sourcePosition;
    @Autowired(name = "ad_id")
    String ad_id;
    @Autowired(name = "ad_name")
    String ad_name;
    @Autowired(name = "key_word")
    String key_word;
    @Autowired(name = "key_word_type")
    String key_word_type;
    @Autowired(name = "isFromLive")
    boolean isFromLive;
    @Autowired(name = "liveId")
    String liveId;
    @Autowired(name = "isFormDealer")
    boolean isFormDealer = false;

    final List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    DelegateAdapter delegateAdapter;
    CommodityDetailBannerAdapter adapter_banner;
    CommodityDetailTimeLimitAdapter adapter_time_limit;
    CommodityDetailFansTimeLimitAdapter adapter_fans_time_limit;
    CommodityDetailInformationAdapter adapter_information;
    CommodityDetailServiceAdapter adapter_service;
    CommodityDetailCommentAdapter adapter_comment;
    CommodityDetailSellerAdapter adapter_seller;
    CommodityDetailDescriptionAdapter adapter_description;
    CommodityDetailRecommendProductAdapter adapter_recommend_product;
    CommodityDetailFootAdapter adapter_foot;

    CommodityCouponDialog commodityCouponDialog;

    RxBus rxBus;

    private int tabPosition = 0;
    String buy_type = "2";
    JSONObject buy_product;
    private boolean isCountDown;
    private ImageDialog vipExclusiveDialog;
    private PurchaseDialog purchaseDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.commodity_detail_activity);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        EventBusManager.register(this);
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(mContext, title_layout);

        status_bar_height = ImmersionBar.getStatusBarHeight(getActivity());
        title_layout.setAlpha(0);
        init();
        add_listener();
        mPresenter.getCommodityDetail(id, "",isFormDealer);
    }

    private void init() {
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(mContext);
        layoutManager.setInitialPrefetchItemCount(10);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemViewCacheSize(16);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(viewPool);
        for (int i = 0; i < 13; i++) {
            viewPool.setMaxRecycledViews(i, 10);
        }
        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);
        if (shareIconCom()) {
            tv_share.setImageResource(R.mipmap.goods_detail_share_icon);
        } else {
            Glide.with(this).load(R.drawable.share).into(tv_share);
        }

        rxBus = RxBus.$();
        UserDataManager.getInstance().requestCustomerInfo(null);
    }


    int distanceY;
    int status_bar_height = 0;
    float search_layout_height = dp2px(44) + status_bar_height;

    private void add_listener() {

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                distanceY += dy;
                VirtualLayoutManager lm = (VirtualLayoutManager) recyclerView.getLayoutManager();
                int first = 0, last = 0, total = 0;
                first = ((LinearLayoutManager) lm).findFirstVisibleItemPosition();
                last = ((LinearLayoutManager) lm).findLastVisibleItemPosition();
                total = recyclerView.getAdapter().getItemCount();
                //System.out.println(first + " ------- > " + last + " ------- > " + total);
                int scrollY = 0;
                SparseIntArray mRecyclerItemHeight = new SparseIntArray();
                View c = recyclerView.getLayoutManager().getChildAt(0); //this is the first visible row
                if (c != null) {
                    scrollY = -c.getTop();
                    mRecyclerItemHeight.put(first, c.getHeight());
                    for (int i = 0; i < first; ++i) {
                        scrollY += mRecyclerItemHeight.get(i); //add all heights of the views that are gone
                    }
                }
                int alpha = (int) (Math.abs(scrollY) / search_layout_height * 255);
                if (alpha > 255) {
                    alpha = 255;
                } else if (alpha < 0) {
                    alpha = 0;
                }
                if (first != 0) {
                    alpha = 255;
                }

                String hexString = Integer.toHexString(alpha);
                if (hexString.length() < 2) {
                    hexString += "0";
                }
                if (alpha > 0) {
                    //StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#" + hexString + "FFFFFF"));
                    iv_back.setImageResource(R.mipmap.goods_detail_back_icon0);
                    if (shareIconCom()) {
                        tv_share.setImageResource(R.mipmap.goods_detail_share_icon0);
                    }
                    material.setVisibility(View.GONE);
                    brandIntroduction.setVisibility(View.GONE);
                } else {
                    //StatusBarUtil.transparencyBar(getActivity());
                    iv_back.setImageResource(R.mipmap.goods_detail_back_icon);
                    if (data != null && data.isShow_material_label()) {
                        material.setVisibility(View.VISIBLE);
                    }
                    if (data != null && !TextUtils.isEmpty(data.getBrand_intro_location_url())){
                        brandIntroduction.setVisibility(View.VISIBLE);
                    }
                    if (shareIconCom()) {
                        tv_share.setImageResource(R.mipmap.goods_detail_share_icon);
                    }
                }
                title_layout.setBackgroundColor(Color.parseColor("#" + hexString + "FFFFFF"));
                ll_jump_con.setAlpha(alpha);
                title_layout.setAlpha(alpha == 0 ? 1 : alpha);

                //System.out.println(first + "scrollY ------- > " + scrollY);
                if (first > detail_index - 1) {
                    iv_back_top.setVisibility(View.VISIBLE);
                } else {
                    iv_back_top.setVisibility(View.GONE);
                }
                if (comment_index == 0) {
                    comment_index = detail_index;
                }
                if (first < comment_index) {
                    //商品tab
                    showTag(0);
                } else if (first < detail_index) {
                    //评价tab
                    showTag(1);
                } else if (first < recommend_index) {
                    //详情tab
                    showTag(2);
                } else {
                    //推荐tab
                    showTag(3);
                }

            }
        });

    }

    @OnClick({R.id.iv_back_layout, R.id.iv_back_top, R.id.tv_share, R.id.rl_recommend, R.id.rl_detail, R.id.rl_cart,R.id.brand_introduction, R.id.material,
            R.id.rl_comment, R.id.rl_goods, R.id.normal_add_cart_btn, R.id.normal_buy_now_btn, R.id.vip_buy, R.id.vip_sell, R.id.single_btn, R.id.rl_kefu,
            R.id.commodity_detail_zsq_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_layout:
                finish();
                break;
            case R.id.tv_share:
                share_click();
                break;
            case R.id.brand_introduction:
                if (data != null && !TextUtils.isEmpty(data.getBrand_intro_location_url())) {
                    startActivitry(BridgeActivity.class,new String[][]{{"url",data.getBrand_intro_location_url()}});
                }
                break;
            case R.id.material:
//                Fragment fragment_material = (Fragment) ARouter.getInstance().build(AroutePath.MATERIAL_FRAGMENT)
//                        .withString("product_id", data.getProduct_id()).withString("market_price",data.getMarket_price())
//                        .withString("market_price_tag",data.getPriceTagBean().getMarket_price_tag())
//                        .withString("base_price_tag",data.getPriceTagBean().getBase_price_tag()).withString("daily_price",data.getDaily_price())
//                        .withString("activity_price_tag",data.getPriceTagBean().getActivity_price_tag())
//                        .withString("goods_title", data.getTitle()).withString("goods_url", data.getShare().getUrl())
//                        .withString("goods_desc", data.getShare().getDesc()).withString("goods_img", data.getShare().getImage())
//                        .withString("goods_lineprice", data.getLine_price()).withString("goods_showprice", data.getPrice())
//                        .withString("goods_commission", data.getCommission()).withString("goods_max_commission", data.getMax_commission())
//                        .withString("goods_double_commission", data.getDouble_commission()).withString("goods_max_double_commission", data.getMax_double_commission())
//                        .withString("goods_type", data.getProduct_type()).withString("goods_integralprice", data.getIntegral_price()).navigation();
//                FragmentHostActivity.openFragment(getActivity(), fragment_material);
                if (data != null && !TextUtils.isEmpty(data.getProduct_id())){
                    ARouter.getInstance().build(AroutePath.MATERIAL_PRODUCT_DETAILS_ACTIVITY)
                            .withString("product_id",data.getProduct_id())
                            .navigation();
                }
                break;
            case R.id.iv_back_top:
                distanceY = 0;
                recyclerView.scrollToPosition(0);
                break;
            case R.id.rl_goods:
                recyclerView.scrollToPosition(commodity_index);
                delay_show_tag(0);
                break;
            case R.id.rl_comment:
                recyclerView.scrollToPosition(comment_index);
                delay_show_tag(1);
                break;
            case R.id.rl_detail:
                recyclerView.scrollToPosition(detail_index);
                delay_show_tag(2);
                break;
            case R.id.rl_recommend:
                recyclerView.scrollToPosition(recommend_index);
                delay_show_tag(3);
                break;
            case R.id.normal_add_cart_btn:

                if (!UserDataManager.getInstance().isSystemLogin()){
                startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                return;
            }
                //采购
                if (data.isCan_purchase()){
                    if (purchaseDialog == null) {
                        purchaseDialog =  new PurchaseDialog(this, new PurchaseDialog.OnChooseListener() {
                            @Override
                            public void cancel() {
                                purchaseDialog.dismiss();
                            }

                            @Override
                            public void confirm() {
                                ARouter.getInstance().build(AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
                                        .withString("product_id",id)
                                        .withString("liveId",liveId)
                                        .navigation();
                                purchaseDialog.dismiss();
                            }
                        });
                    }
                    purchaseDialog.show();
                    return;
                }

                if (!TextUtils.isEmpty(data.getIntegral_product_vip_exclusive()) && "1".equals(data.
                        getIntegral_product_vip_exclusive()) && (TextUtils.isEmpty(UserDataManager.getInstance().getRoleLevel())
                        || Integer.parseInt(UserDataManager.getInstance().getRoleLevel()) < 10)){
                    showVipExclusiveDialog();
                }else {
                    show_sku_select_dialog(0);
                }
                break;
            case R.id.normal_buy_now_btn:

                if (!UserDataManager.getInstance().isSystemLogin()){
                    startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                    return;
                }
                //采购
                if (data.isCan_purchase()){
                    if (purchaseDialog == null) {
                        purchaseDialog =  new PurchaseDialog(this, new PurchaseDialog.OnChooseListener() {
                            @Override
                            public void cancel() {
                                purchaseDialog.dismiss();
                            }

                            @Override
                            public void confirm() {
                                ARouter.getInstance().build(AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
                                        .withString("product_id",id)
                                        .withString("liveId",liveId)
                                        .navigation();
                                purchaseDialog.dismiss();
                            }
                        });
                    }
                    purchaseDialog.show();
                    return;
                }

                if (!TextUtils.isEmpty(data.getIntegral_product_vip_exclusive()) && "1".equals(data.
                        getIntegral_product_vip_exclusive()) && (TextUtils.isEmpty(UserDataManager.getInstance().getRoleLevel())
                        || Integer.parseInt(UserDataManager.getInstance().getRoleLevel()) < 10)){
                    showVipExclusiveDialog();
                }else {
                long stockX = 0;
                if (!TextUtils.isEmpty(data.getStock())) {
                    stockX = Long.valueOf(data.getStock());
                }
                if (stockX < 1) {
                    return;
                }
                if ("0".equals(data.getStatus())) {
                    return;
                }
                show_sku_select_dialog(1);
                }
                break;
            case R.id.vip_buy:
                if ("1".equals(data.getActivity_type())) {
                    show_sku_select_dialog(1);
                } else {
                    show_sku_select_dialog(2);
                }
                break;
            case R.id.vip_sell:
                share_click();
                break;
            case R.id.single_btn:
                long stock = 0;
                if (!TextUtils.isEmpty(data.getStock())) {
                    stock = Long.valueOf(data.getStock());
                }
                if (stock < 1) {
                    return;
                }
                if ("0".equals(data.getStatus())) {
                    return;
                }
                if ("立即分享".equals(single_btn.getText().toString().trim())) {
                    share_click();
                } else {
                    show_sku_select_dialog(1);
                }
                break;
            case R.id.rl_kefu:

                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Information info = SobotManager.getBaseInfo();
                    SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                    String sobot_app_key = "", sobot_flow_company_id = "", sobot_flow_group_id = "";
                    if (data != null && data.getSeller() != null) {
                        sobot_app_key = data.getSeller().getSobot_app_key();
                        sobot_flow_company_id = data.getSeller().getSobot_flow_company_id();
                        sobot_flow_group_id = data.getSeller().getSobot_flow_group_id();
                    }
                    if (!TextUtils.isEmpty(sobot_app_key)) {
                        info.setAppkey(sobot_app_key);
                        SobotManager.setSobotFlow(mContext, sobot_flow_company_id, sobot_flow_group_id, "0");
                    }
                    if (data != null) {
                        Map<String, String> customInfo = new HashMap<String, String>();
                        customInfo.put("product_name", data.getTitle());
                        String product_image = "";
                        if (data.getImages() != null && data.getImages().size() > 0) {
                            product_image = data.getImages().get(0);
                        }
                        customInfo.put("product_image", product_image);
                        info.setCustomInfo(customInfo);
                        //咨询内容
                        ConsultingContent consultingContent = new ConsultingContent();
                        //咨询内容标题，必填
                        consultingContent.setSobotGoodsTitle(data.getTitle());
                        //咨询内容图片，选填 但必须是图片地址
                        consultingContent.setSobotGoodsImgUrl(product_image);
                        //咨询来源页，必填
                        consultingContent.setSobotGoodsFromUrl(product_image);
                        //描述，选填
                        //consultingContent.setSobotGoodsDescribe("XXX超级电视 S5");
                        //标签，选填
                        consultingContent.setSobotGoodsLable("¥" + data.getPrice());
                        //转人工后是否自动发送
                        consultingContent.setAutoSend(true);
                        //可以设置为null
                        info.setConsultingContent(consultingContent);
                        //发送商品卡片消息接口
                        SobotApi.sendCardMsg(mContext, consultingContent);
                    }
                    SobotApi.setHyperlinkListener(new SobotHyperlinkListener());
                    SobotApi.startSobotChat(CommodityDetailActivity.this, info);

                } else {
                    startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                }
                break;
            case R.id.rl_cart:
                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.SHOP_CART_FRAGMENT)
                            .withString("from", "activity")
                            .navigation();
                    FragmentHostActivity.openFragment(getActivity(), fragment);
                } else {
                    startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                }

                break;
            case R.id.commodity_detail_zsq_btn: {
                //赠送
                show_sku_select_dialog(1);
            }
                break;
        }
    }

    ConfirmDialog confirmDialog;

    private void share_click() {
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
            share();
        } else {
            confirmDialog = new ConfirmDialog(CommodityDetailActivity.this, "您暂未登录", "未登录状态的分享将会无法绑定粉丝\n" + "继续分享吗", "继续分享", "去登录", 0);
            confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    confirmDialog.dismiss();
                    share();
                }

                @Override
                public void confirm() {
                    confirmDialog.dismiss();
                    startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                }
            });
            confirmDialog.show();
        }

    }

    private void showVipExclusiveDialog(){
        if (vipExclusiveDialog == null){
            vipExclusiveDialog = new ImageDialog("会员权益商品",this,"", SystemConfigStorage.getInstance().getFansUrl(),"","",null);
        }
        vipExclusiveDialog.show();
        vipExclusiveDialog.setImageResource(R.mipmap.vip_exclusive_picture);
    }

    SkuSelectDialog skuSelectDialog;
    String max_discount_coupon_id = "0";

    private void show_sku_select_dialog(int bottom_btn_type) {
        if (data == null) {
            showToast("商品不存在");
            return;
        }

        if (data.isProduct_is_agent()&&data.getAgent_info()!=null&&!data.getAgent_info().isCan_buy_agent()){
            showToast(data.getAgent_info().getToast_info());
            return;
        }

        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
            startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
            return;
        }


        skuSelectDialog = new SkuSelectDialog(CommodityDetailActivity.this, data, bottom_btn_type);

        skuSelectDialog.setSkuSelectCallBack(new SkuSelectDialog.SkuSelectCallBack() {
            @Override
            public void onSkuSelect(String product_id, String skuName, String num, int operate,String max_discount_coupon_id,String couponId,String couponName) {
                if (operate == 0) {
                    show_progressDialog();
                    mPresenter.addCart(product_id, num);
                } else if (operate == 1) {

                    CommodityDetailActivity.this.max_discount_coupon_id = max_discount_coupon_id;
                    buy_product = new JSONObject();
                    try {
                        buy_product.put(product_id, Integer.valueOf(num));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!"0".equals(max_discount_coupon_id)) {
                        //调用领券接口
                        show_progressDialog();
                        mPresenter.pickUpSalesrule(max_discount_coupon_id, id);
                    } else {
                        if (!isCountDown) {
                            show_progressDialog();
                            mPresenter.confirm_order(buy_product.toString(), buy_type, data.getSale_type());
                        }
                    }
                } else if (operate == 2) {

                    CommodityDetailActivity.this.max_discount_coupon_id = max_discount_coupon_id;
                    buy_product = new JSONObject();
                    try {
                        buy_product.put(product_id, Integer.valueOf(num));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!isCountDown) {
                        show_progressDialog();
                        mPresenter.confirm_order(buy_product.toString(), buy_type,data.getSale_type());
                    }
                }
            }
        });

        skuSelectDialog.show();
    }

    private void delay_show_tag(int position) {
        tabPosition = position;
        root.postDelayed(new Runnable() {
            @Override
            public void run() {
                showTag(position);
            }
        }, 200);
    }

    public void showTag(int position) {
        tabPosition = position;
        if (data != null && data.getProduct_type() != null && "4".equals(data.getProduct_type()) && position == 3) {
            position = 2;
        }
        tvTagGoods.setVisibility(View.INVISIBLE);
        tvTagComment.setVisibility(View.INVISIBLE);
        tvTagDetail.setVisibility(View.INVISIBLE);
        tvTagRecommend.setVisibility(View.INVISIBLE);
        tvTagGoods1.setTextColor(0xff525866);
        tvTagComment1.setTextColor(0xff525866);
        tvTagDetail1.setTextColor(0xff525866);
        tvTagRecommend1.setTextColor(0xff525866);

        switch (position) {
            case 0:
                tvTagGoods.setVisibility(View.VISIBLE);
                tvTagGoods1.setTextColor(getResources().getColor(R.color.our_gongzhu_color));
                break;
            case 1:
                tvTagComment.setVisibility(View.VISIBLE);
                tvTagComment1.setTextColor(getResources().getColor(R.color.our_gongzhu_color));
                break;
            case 2:
                tvTagDetail.setVisibility(View.VISIBLE);
                tvTagDetail1.setTextColor(getResources().getColor(R.color.our_gongzhu_color));
                break;
            case 3:
                tvTagRecommend.setVisibility(View.VISIBLE);
                tvTagRecommend1.setTextColor(getResources().getColor(R.color.our_gongzhu_color));
                break;
        }
    }

    private void share() {
        if (data == null) {
            return;
        }
        String max_commission = data.getMax_commission();
        if (Float.valueOf(data.getMax_double_commission()) > Float.valueOf(max_commission)) {
            max_commission = data.getMax_double_commission();
        }
        CommodityShareMessage shareMessage = data.getShare();
        ShareCommonDialog shareComDialog = new ShareCommonDialog(this);
        shareComDialog.show();
        String product_type = data.getProduct_type();
        shareComDialog.setSData("商品",!TextUtils.isEmpty(ad_id)?ad_id:sourcePageId, data.getProduct_id(),data.getTitle(),!TextUtils.isEmpty(ad_name)?ad_name:!TextUtils.isEmpty(product_sourcepage)?product_sourcepage:sourcePage,data.getShare().getUrl());
        shareComDialog.setShareData(shareMessage.getTitle(), shareMessage.getUrl(),
                shareMessage.getDesc(), shareMessage.getImage(), shareMessage.getJumpType()
                , shareMessage.getPath(), shareMessage.getMini_program_image());
        shareComDialog.setProduct_type(Integer.parseInt(product_type));
        shareComDialog.setCommission(("4".equals(product_type) || "3".equals(product_type)
                        || "2".equals(product_type) ) ? "0" :
                        data.getCommission(),
                max_commission);
        shareComDialog.shareGoodsDetail(new ShareProductBean(data.getPrice(),data.getIntegral_price(),data.getPriceTagBean().getMarket_price_tag()
                ,data.getMarket_price(),data.getPriceTagBean().getBase_price_tag(),data.getDaily_price(),data.getPriceTagBean().getActivity_price_tag(),product_type));
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusManager.unRegister(this);
        if (adapter_banner != null) {
            adapter_banner.destroy();
        }
    }

    int index = 0;
    int commodity_index, comment_index, detail_index, recommend_index;
    CommodityDetailData data;

    @Override
    public void showCommodityDetail(CommodityDetailData data) {

        if (!TextUtils.isEmpty(data.getVip_level())) {
            UserDataManager.getInstance().updateUserLevel(data.getVip_level());
        }

        if (shareIconCom()) {
            tv_share.setImageResource(R.mipmap.goods_detail_share_icon);
        } else {
            Glide.with(this).load(R.drawable.share).into(tv_share);
        }

        this.data = data;
        adapters.clear();
        delegateAdapter.setAdapters(adapters);
        recyclerView.setAdapter(delegateAdapter);
        index = 0;


        //banner区
        List<String> banner_images = data.getImages();
        if (adapters.contains(adapter_banner)) {
            adapters.remove(adapter_banner);
        }
        if (banner_images != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_banner = new CommodityDetailBannerAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_banner, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_banner);
            index++;
        }

        //限时购
        if (adapters.contains(adapter_time_limit)) {
            adapters.remove(adapter_time_limit);
        }
        if (data.getSingle_promotion() != null && "1".equals(data.getActivity_type())) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_time_limit = new CommodityDetailTimeLimitAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_time_limit, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_time_limit);
            index++;
        }

        //粉丝福利限时购
        if (adapters.contains(adapter_fans_time_limit)) {
            adapters.remove(adapter_fans_time_limit);
        }
        if (data.getSingle_promotion() != null && data.getSingle_promotion().getType() != null && "2".equals(data.getActivity_type())) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_fans_time_limit = new CommodityDetailFansTimeLimitAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_time_fans_limit, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_fans_time_limit);
            index++;
        }


        //商品基础信息区域
        if (adapters.contains(adapter_information)) {
            adapters.remove(adapter_information);
        }
        boolean hasInformation = true;
        if (hasInformation) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_information = new CommodityDetailInformationAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data,true) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_information, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_information.setOnInformationCallback(new CommodityDetailInformationAdapter.OnInformationCallback() {
                @Override
                public void favoriteClick() {

                    if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                        startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                    } else {
                        if (data.isIs_favorite()) {
                            mPresenter.removeFavorite(data.getProduct_id());
                        } else {
                            mPresenter.addFavorite(data.getProduct_id());
                        }
                    }
                }

                @Override
                public void upgradeClick() {
                    show_sku_select_dialog(1);
                }
            });
            adapters.add(adapter_information);
            //commodity_index = index;
            index++;
        }

        //优惠 服务 发货
        if (adapters.contains(adapter_service)) {
            adapters.remove(adapter_service);
        }
        boolean hasService = true;
        if (hasService) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_service = new CommodityDetailServiceAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_service, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_service.setOnServiceCallBack(new CommodityDetailServiceAdapter.OnServiceCallBack() {
                @Override
                public void couponClick() {
                    commodityCouponDialog = new CommodityCouponDialog(mContext, "优惠", data.getCoupons(), data.getPromotions(), data.getPromotion_desc(), data.getMeet_reduce_promotion());
                    commodityCouponDialog.show();
                    commodityCouponDialog.setOnButtonClickListener(new CommodityCouponDialog.OnButtonClickListener() {
                        @Override
                        public void btnClick(String code, int position) {
                            if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                                startActivitry(QuickLoginActivity.class,new String[][]{{"intentSource","商品详情"}});
                            } else {
                                show_progressDialog();
                                mPresenter.pickUpSalesrule(code,id);
                                CouponMessage coupon = data.getCoupons().get(position);
                                }
                        }

                        @Override
                        public void meetReduceCallback() {
                        }

                        @Override
                        public void giveawayCallback(String activity_id, String activity_name) {

                        }
                    });
                }
                @Override
                public void serviceClick() {
                    ActivityDialog dialog3 = new ActivityDialog(mContext, "服务说明", new CommodityServiceAdapter(mContext, data.getServices()));
                    dialog3.show();
                }
            });
            adapters.add(adapter_service);
            index ++;
        }

        //评论
        if (adapters.contains(adapter_comment)) {
            adapters.remove(adapter_comment);
        }
        CommodityComment commodityComment = data.getComment();
        if(commodityComment != null){
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_comment = new CommodityDetailCommentAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_comment, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_comment);
            comment_index = index;
            index ++;
        }

        //店铺
        if (adapters.contains(adapter_seller)) {
            adapters.remove(adapter_seller);
        }
        SellerMessage sellerMessage = data.getSeller();
        if(sellerMessage != null){
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_seller = new CommodityDetailSellerAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data,!isFormDealer) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_seller, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_seller);
            index ++;
        }

        //详情
        if (adapters.contains(adapter_description)) {
            adapters.remove(adapter_description);
        }
        boolean hasDescription = true;
        if(hasDescription){
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_description = new CommodityDetailDescriptionAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_description, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_description);
            detail_index = index;
            index ++;
        }

        //推荐商品
        if (adapters.contains(adapter_recommend_product)) {
            adapters.remove(adapter_recommend_product);
        }
        List<ProductMessage> recommend_products = data.getRecommend_products();
        if(recommend_products != null && recommend_products.size() > 0){
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_recommend_product = new CommodityDetailRecommendProductAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_recommend_products, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_recommend_product);
            recommend_index = index;
            index ++;
        }

        //底部
        boolean hasFoot = true;
        if (adapters.contains(adapter_foot)) {
            adapters.remove(adapter_foot);
        }
        if(hasFoot){
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_foot = new CommodityDetailFootAdapter(CommodityDetailActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.commodity_detail_foot, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_foot);
            index ++;
        }

        delegateAdapter.setAdapters(adapters);

        if (!isFormDealer) {
            //底部按钮展示
            display_bottom_btn(data);
        }
        //控制分享隐藏
        if(data.getShare().isCan_share()){
            tv_share.setVisibility(View.VISIBLE);
        }else{
            tv_share.setVisibility(View.GONE);
        }
        //控制品牌介绍
        if(!TextUtils.isEmpty(data.getBrand_intro_location_url())){
            brandIntroduction.setVisibility(View.VISIBLE);
        } else {
            brandIntroduction.setVisibility(View.GONE);
        }
        //控制素材圈隐藏
        if(data.isShow_material_label()){
            material.setVisibility(View.VISIBLE);
        } else {
            material.setVisibility(View.GONE);
        }
        //礼包商品没有推荐商品
        if("4".equals(data.getProduct_type())){
            rl_recommend.setVisibility(View.GONE);
        }

    }


    //分享图标显示样式
    private boolean shareIconCom(){
        if (data != null && data.isProduct_is_agent()) return true;
        if (!UserDataManager.getInstance().isSystemLogin()) return true;
        if (data != null) {
            if (data.isIs_dealer()){
                return Integer.parseInt(UserDataManager.getInstance().getRoleLevel())>=10;
            }else {
                return false;
            }
        }
        return false;
    }

    private void display_bottom_btn(CommodityDetailData data) {
        if (Integer.parseInt(data.getActivity_type()) == 3) {
                ll_bottom.setVisibility(View.GONE);
                zsqBottomView.setVisibility(View.VISIBLE);
            } else {
                ll_bottom.setVisibility(View.VISIBLE);
                zsqBottomView.setVisibility(View.GONE);
            }
        float coupon_price_amount = Float.valueOf(data.getAfter_coupon_price());
        if(Integer.valueOf(data.getCart_num()) > 0){
            tvCartBadge.setBadgeCount(data.getCart_num());
            tvCartBadge.setVisibility(View.VISIBLE);
        } else {
            tvCartBadge.setVisibility(View.INVISIBLE);
        }
        String product_type = data.getProduct_type();
        long stock = 0;
        if(!TextUtils.isEmpty(data.getStock())){
            stock = Long.valueOf(data.getStock());
        }

        if("0".equals(data.getStatus())){
            normal_layout.setVisibility(View.VISIBLE);
            vip_bottom_layout.setVisibility(View.GONE);
            single_btn_layout.setVisibility(View.GONE);
            normal_add_cart_btn.setVisibility(View.GONE);
            normal_buy_now_btn.setVisibility(View.VISIBLE);
            normal_buy_now_btn.setText("已下架");
            normal_buy_now_btn.setBackgroundResource(R.drawable.detail_sellout_bkg);
            return;
        }

        if(stock < 1){
            normal_layout.setVisibility(View.VISIBLE);
            vip_bottom_layout.setVisibility(View.GONE);
            single_btn_layout.setVisibility(View.GONE);
            normal_add_cart_btn.setVisibility(View.GONE);
            normal_buy_now_btn.setVisibility(View.VISIBLE);
            normal_buy_now_btn.setText("已售罄");
            normal_buy_now_btn.setBackgroundResource(R.drawable.detail_sellout_bkg);
            return;
        }

            if ("1".equals(product_type)) {
                //登录用户 + (非经销商||(经销商&&(v0和v0.5)))
                if (coupon_price_amount<=0&&!data.isProduct_is_agent()&&UserDataManager.getInstance().isSystemLogin()&&(!data.isIs_dealer()||
                        (data.isIs_dealer()&&Integer.parseInt(UserDataManager.getInstance().getRoleLevel())<10))) {
                    if (Integer.parseInt(UserDataManager.getInstance().getRoleLevel())==0){
                        vip_buy_name.setText("立即购买");
                        vip_save_money.setVisibility(View.GONE);
                    }
                    normal_layout.setVisibility(View.GONE);
                    vip_bottom_layout.setVisibility(View.VISIBLE);
                    single_btn_layout.setVisibility(View.GONE);
                }else {
                    //普通商品
                    normal_layout.setVisibility(View.VISIBLE);
                    vip_bottom_layout.setVisibility(View.GONE);
                    single_btn_layout.setVisibility(View.GONE);
                    normal_add_cart_btn.setText("加入购物车");
                    normal_buy_now_btn.setText("立即购买");
                    if ("1".equals(data.getActivity_type())) {
                        normal_add_cart_btn.setVisibility(View.GONE);
                        normal_buy_now_btn.setVisibility(View.VISIBLE);
                        normal_buy_now_btn.setBackgroundResource(R.drawable.detail_buy_bkg1);
                        //券后价
                        display_after_coupon_price_btn(coupon_price_amount, normal_buy_now_btn, 1);
                    } else {
                        normal_add_cart_btn.setVisibility(View.VISIBLE);
                        normal_buy_now_btn.setVisibility(View.VISIBLE);
                        normal_add_cart_btn.setBackgroundResource(R.drawable.detail_shopcart_bkg);
                        normal_buy_now_btn.setBackgroundResource(R.drawable.detail_buy_bkg0);
                        //券后价
                        display_after_coupon_price_btn(coupon_price_amount, normal_buy_now_btn, 0);
                    }
                }

            } else if ("2".equals(product_type)) {
                //金币商品
                normal_layout.setVisibility(View.VISIBLE);
                vip_bottom_layout.setVisibility(View.GONE);
                single_btn_layout.setVisibility(View.GONE);
                normal_add_cart_btn.setText("加入购物车");
                normal_buy_now_btn.setText("立即兑换");
                //券后价
                display_after_coupon_price_btn(coupon_price_amount, normal_buy_now_btn, 0);

            } else if ("3".equals(product_type)) {
                //0元试用
                normal_layout.setVisibility(View.GONE);
                vip_bottom_layout.setVisibility(View.GONE);
                single_btn_layout.setVisibility(View.VISIBLE);
                single_btn.setText("立即领取");
                //券后价
                display_after_coupon_price_btn(coupon_price_amount, single_btn, 1);
            } else if ("4".equals(product_type)) {
                //礼包
                normal_layout.setVisibility(View.GONE);
                vip_bottom_layout.setVisibility(View.GONE);
                single_btn_layout.setVisibility(View.VISIBLE);
                single_btn.setText(Integer.parseInt(UserDataManager.getInstance().getRoleLevel())<=0?"立即购买":"立即分享");
                //券后价
                display_after_coupon_price_btn(coupon_price_amount, single_btn, 1);
            }

        //新人专享 特殊处理
        List<ProductTag> tags = data.getTags();
        for (ProductTag tag : tags) {
            if ("2".equals(tag.getType())) {
                normal_layout.setVisibility(View.VISIBLE);
                vip_bottom_layout.setVisibility(View.GONE);
                single_btn_layout.setVisibility(View.GONE);
                normal_add_cart_btn.setText("加入购物车");
                normal_buy_now_btn.setText("立即购买");
                normal_add_cart_btn.setVisibility(View.GONE);
                normal_buy_now_btn.setVisibility(View.VISIBLE);
                normal_buy_now_btn.setBackgroundResource(R.drawable.detail_buy_bkg1);
                //券后价
                display_after_coupon_price_btn(coupon_price_amount, normal_buy_now_btn, 1);
                continue;
            }
        }

        String commission = data.getCommission();
        if (!TextUtils.isEmpty(data.getDouble_commission()) && Float.valueOf(data.getDouble_commission()) > 0) {
            commission = data.getDouble_commission();
        }
        if (TextUtils.isEmpty(data.getSave_price()) || Double.parseDouble(data.getSave_price()) == 0){
            vip_save_money.setText("");
        }else {
            vip_save_money.setText("(省¥" + data.getSave_price() + ")");
        }
        if (TextUtils.isEmpty(commission) || Double.parseDouble(commission) == 0) {
            vip_earn_money.setText("");
        }else {
            vip_earn_money.setText("(赚¥" + commission + ")");
        }

        //兼容5.1.0时会员体系未上
        if (Integer.valueOf(UserDataManager.getInstance().getRoleLevel()) <= 0){
            vipEarnName.setText("分享");
            vip_earn_money.setVisibility(View.GONE);
        }else {
            vipEarnName.setText("卖");
            vip_earn_money.setVisibility(View.VISIBLE);

        }

    }

    private void display_after_coupon_price_btn(float coupon_price_amount, TextView btn, int type) {
        //type 0 换行
        if (coupon_price_amount >= 0) {
            if (type == 0) {
                String content = "领券购买" + "\n¥" + data.getAfter_coupon_price() + (data.isIs_same_coupon_price() ? "" : "起");
                SpannableString spannableString = new SpannableString(content);
                spannableString.setSpan(new RelativeSizeSpan(0.87f), 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString.setSpan(new RelativeSizeSpan(0.73f), 5, content.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                btn.setText(spannableString);
            } else {
                btn.setText("领券购买" + "¥" + data.getAfter_coupon_price() + (data.isIs_same_coupon_price() ? "" : "起"));
            }
        }
    }

    @Override
    public void getCommodityDetailFailed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void pickUpSalesruleSuccess(String coupon_code, String msg) {
        dismiss_progressDialog();
        showToast(msg);
        receive_coupon_result_next();
//        List<CouponMessage> list = data.getCoupons();
//        for (CouponMessage bean : list) {
//            if (coupon_code.equals(bean.getCoupon_code())) {
//                bean.setIs_receive(true);
//            }
//        }
//        commodityCouponDialog.notifyDataChange(list,data.getPromotions(),data.getPromotion_desc());

    }

    @Override
    public void pickUpSalesruleFailed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
        receive_coupon_result_next();
    }

    private void receive_coupon_result_next() {
        if (!"0".equals(max_discount_coupon_id) && !isCountDown) {
            max_discount_coupon_id = "0";
            mPresenter.confirm_order(buy_product.toString(), buy_type, data.getSale_type());
        }
    }

    @Override
    public void favoriteFailed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void removeFavoriteSuccess() {
        dismiss_progressDialog();
        showToast("移除收藏成功");
        data.setIs_favorite(!data.isIs_favorite());
        adapter_information.notifyDataSetChanged();
    }

    @Override
    public void addFavoriteSuccess() {
        dismiss_progressDialog();
        showToast("收藏成功");
        data.setIs_favorite(!data.isIs_favorite());
        adapter_information.notifyDataSetChanged();
    }

    @Override
    public void addCartSuccess(AddShopCartBean addShopCartBean) {
        dismiss_progressDialog();
        showToast("加入购物车成功");
        tvCartBadge.setVisibility(View.VISIBLE);
        tvCartBadge.setBadgeCount(addShopCartBean.data.cartNum);
        if (skuSelectDialog != null) {
            skuSelectDialog.dismiss();
        }
    }

    @Override
    public void addCartFailed(String msg) {
        showToast(msg);
        dismiss_progressDialog();
    }

    @Override
    public void confirm_order_success(ConfirmOrderData data, String code) {
        dismiss_progressDialog();
        Toast tst = Toast.makeText(this, "", Toast.LENGTH_LONG);
        if (code.equals("20001")) {
            isCountDown = true;
            Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.computation())
                    .take(4).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Long aLong) {
                    tst.setText(data.getText() + (3 - aLong) + "s");
                    tst.show();
                }

                @Override
                public void onError(Throwable e) {
                    isCountDown = false;
                }

                @Override
                public void onComplete() {
                    isCountDown = false;
                    if (!TextUtils.isEmpty(data.getUrl())) {
                        CommonUtil.goAnyWhere(CommodityDetailActivity.this, data.getUrl(), "", "", "", "");
                    }
                }
            });
        } else {
            ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY)
                    .withString("convert", this.data.getProduct_type())
                    .withString("buy_type", "2")
                    .withString("live_room_id",liveId == null ? "0" : liveId)
                    .withString("saleType",this.data.getSale_type())
                    .withString("buy_product", buy_product.toString())
                    .withSerializable("confirm_order_data", data).navigation();
        }
    }

    @Override
    public void setSaleRemainSuccess() {

    }

    @Override
    public void confirm_order_failed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void setSaleRemainFail(String msg) {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    //TODO:通知登录成功
    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        if (data != null && data.isShow_material_label()) {
            material.setVisibility(View.VISIBLE);
        } else {
            material.setVisibility(View.GONE);
        }
        if (data != null && !TextUtils.isEmpty(data.getBrand_intro_location_url())) {
            brandIntroduction.setVisibility(View.VISIBLE);
        } else {
            brandIntroduction.setVisibility(View.GONE);
        }
        UserDataManager.getInstance().requestCustomerInfo(null);
        if (mPresenter != null) {
            mPresenter.getCommodityDetail(id, "",isFormDealer);
        }
    }






}
